package com.whcoding.easypoi.util;


import org.apache.commons.compress.utils.IOUtils;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileItemFactory;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.springframework.http.MediaType;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;


import java.io.*;

/**
 * @program: spring-boot-learning
 * @description:
 * @author: whcoding
 * @create: 2022-09-09 11:29
 **/
public class FileToMultipartFile {

	public static FileItem createFileItem(String filePath, String fileName){
		String fieldName = "file";
		FileItemFactory factory = new DiskFileItemFactory(16, null);
		FileItem item = factory.createItem(fieldName, "text/plain", false,fileName);
		File newfile = new File(filePath);
		int bytesRead = 0;
		byte[] buffer = new byte[8192];
		try (FileInputStream fis = new FileInputStream(newfile);
			 OutputStream os = item.getOutputStream()) {
			while ((bytesRead = fis.read(buffer, 0, 8192))!= -1)
			{
				os.write(buffer, 0, bytesRead);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return item;
	}


}
